<template>
    <div class="cart-page">
        <div class="container">
            <Bread>
                <BreadItem to="/">首页</BreadItem>
                <BreadItem>购物车</BreadItem>
            </Bread>
            <div class="cart">
                <table>
                    <thead>
                        <tr>
                            <th width="120">
                                <Checkbox v-model="selectedAll" @click="handleAll">全选</Checkbox>
                            </th>
                            <th width="400">商品信息</th>
                            <th width="220">单价</th>
                            <th width="180">数量</th>
                            <th width="180">小计</th>
                            <th width="140">操作</th>
                        </tr>
                    </thead>
                    <!-- 有效商品 -->
                    <tbody v-if="validList.length">
                        <tr v-for="item in validList" :key="item.id">
                            <td>
                                <Checkbox v-model="item.selected" @click="handleChecked(item)" />
                            </td>
                            <td>
                                <div class="goods">
                                    <RouterLink to="/"><img :src="item.picture" alt=""></RouterLink>
                                    <div>
                                        <p class="name ellipsis">{{ item.name }}</p>
                                        <!-- 选择规格组件 -->
                                    </div>
                                </div>
                            </td>
                            <td class="tc">
                                <p>&yen;{{ item.price }}</p>
                                <p v-if="item.price < item.nowOriginalPrice">比加入时降价 <span class="red">&yen;{{
                                        item.nowOriginalPrice - item.price
                                }}</span></p>
                            </td>
                            <td class="tc">
                                <NumBox :showLabel="false" v-model="item.count" @update:modelValue="updateNum(item)" />
                            </td>
                            <td class="tc">
                                <p class="f16 red">&yen;{{ item.price * item.count }}</p>
                            </td>
                            <td class="tc">
                                <p><a href="javascript:;">移入收藏夹</a></p>
                                <p><a class="green" href="javascript:;" @click="handleDel(item)">删除</a></p>
                                <p><a href="javascript:;">找相似</a></p>
                            </td>
                        </tr>
                    </tbody>
                    <!-- 无效商品 -->
                    <tbody v-if="invalidList.length">
                        <tr>
                            <td colspan="6">
                                <h3 class="tit">失效商品</h3>
                            </td>
                        </tr>
                        <tr v-for="item in invalidList" :key="item.id">
                            <td>
                                <Checkbox v-model="item.selected" style="color:#eee;" />
                            </td>
                            <td>
                                <div class="goods">
                                    <RouterLink to="/"><img :src="item.picture" alt=""></RouterLink>
                                    <div>
                                        <p class="name ellipsis">{{ item.name }}</p>
                                        <p class="attr">{{ item.attrsText }}</p>
                                    </div>
                                </div>
                            </td>
                            <td class="tc">
                                <p>&yen;{{ item.price }}</p>
                            </td>
                            <td class="tc">{{ item.count }}</td>
                            <td class="tc">
                                <p>&yen;{{ item.price * item.count }}</p>
                            </td>
                            <td class="tc">
                                <p><a class="green" href="javascript:;" @click="handleDel(item)">删除</a></p>
                                <p><a href="javascript:;">找相似</a></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <!-- 操作栏 -->
            <div class="action">
                <div class="batch">
                    <Checkbox v-model="selectedAll" @click="handleAll">全选</Checkbox>
                    <a href="javascript:;" @click="handleDel">删除商品</a>
                    <a href="javascript:;">移入收藏夹</a>
                    <a href="javascript:;" @click="handleInvalid">清空失效商品</a>
                </div>
                <div class="total">
                    共 {{ validList.length }} 件商品，已选择 {{ selectedNum }} 件，商品合计：
                    <span class="red">¥{{ total }}</span>
                    <Button type="primary" @click="checkout">下单结算</Button>
                </div>
            </div>
            <!-- 猜你喜欢 -->
            <ProductRelevant />
        </div>
    </div>
</template>
  <script setup>
import ProductRelevant from '@/views/product/components/product-relevant.vue'
import { getCartList, checkAllCart, updateCart, deleteCart } from '@/api/cart'
import { computed, onMounted, ref } from 'vue';
import Confirm from '@/components/lib/Confirm.js'
import Message from '@/components/lib/Message'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()
onMounted(() => {
    getList()
})

const cartList = ref([])
const getList = async () => {
    const { result } = await getCartList()
    cartList.value = result
}

// 无效商品列表
const invalidList = computed(() => {
    return cartList.value.filter(item => !(item.stock > 0 && item.isEffective))
})
// 有效商品列表
const validList = computed(() => {
    return cartList.value.filter(item => (item.stock > 0 && item.isEffective))
})
// 全选v-model
const selectedAll = computed(() => {
    return validList.value.every(item => item.selected === true)
})
// 已选中商品数量
const selectedNum = computed(() => {
    return validList.value.filter(item => item.selected).length
})
// 总价格
const total = computed(() => {
    const num = ref(0)
    validList.value.map(item => {
        if (item.selected)
            num.value += item.count * item.price
    })
    return num
})
// 全选
const handleAll = async () => {
    const params = {
        selected: !selectedAll.value,
        ids: validList.value.map(item => item.skuId)
    }
    await checkAllCart(params)
    getList()
}
// 单选
const handleChecked = async (item) => {
    await updateCart(item.skuId, { selected: item.selected })
    getList()
}
// 更新数量
const updateNum = async (item) => {
    await updateCart(item.skuId, { count: item.count })
    getList()
}
// 删除
const handleDel = async (item) => {
    const res = ref(null)
    const ids = ref(null)
    if (item.id) {
        res.value = await Confirm({ text: '亲，您是否确认删除商品' })
        ids.value = [item.skuId]
    } else {
        // ids.value = validList.value.filter(item => item.selected===true)
        if (!ids.value.length) {
            Message({ type: 'error', text: '请至少选择一条记录' })
            return
        }
        res.value = await Confirm({ text: '亲，您是否确认删除选中的商品' })
        // ids.value = validList.map(item => item.selected)
    }

    if (res.value)
        await deleteCart({ ids })
    Message({ type: 'success', text: '删除成功' })
    getList()
}
// 清空失效品
const handleInvalid = async () => {
    const ids = ref([])
    ids.value = invalidList.value.filter(item => item.skuId)
    await deleteCart({ ids })
    Message({ type: 'success', text: '删除成功' })
    getList()
}
// 结算
const checkout = () => {
    if (!selectedNum.value)
        Message({ type: 'error', text: '请至少选择一件商品' })

    if (!userStore.token)
        router.push('/login')
    else
        router.push('/member/checkout')
}
</script>
<style scoped lang="scss">
.tc {
    text-align: center;

    .numbox {
        margin: 0 auto;
        width: 120px;
    }
}

.red {
    color: $priceColor;
}

.green {
    color: $mainColor
}

.f16 {
    font-size: 16px;
}

.goods {
    display: flex;
    align-items: center;

    img {
        width: 100px;
        height: 100px;
    }

    >div {
        width: 280px;
        font-size: 16px;
        padding-left: 10px;

        .attr {
            font-size: 14px;
            color: #999;
        }
    }
}

.action {
    display: flex;
    background: #fff;
    margin-top: 20px;
    height: 80px;
    align-items: center;
    font-size: 16px;
    justify-content: space-between;
    padding: 0 30px;

    .checkbox {
        color: #999;
    }

    .batch {
        a {
            margin-left: 20px;
        }
    }

    .red {
        font-size: 18px;
        margin-right: 20px;
        font-weight: bold;
    }
}

.tit {
    color: #666;
    font-size: 16px;
    font-weight: normal;
    line-height: 50px;
}

.cart-page {
    .cart {
        background: #fff;
        color: #666;

        table {
            border-spacing: 0;
            border-collapse: collapse;
            line-height: 24px;

            th,
            td {
                padding: 10px;
                border-bottom: 1px solid #f5f5f5;

                &:first-child {
                    text-align: left;
                    padding-left: 30px;
                    color: #999;
                }
            }

            th {
                font-size: 16px;
                font-weight: normal;
                line-height: 50px;
            }
        }
    }
}
</style>